package dev.alm.cqtakeoutservice.controller;

import dev.alm.cqtakeoutservice.common.CR;
import dev.alm.cqtakeoutservice.entity.User;
import dev.alm.cqtakeoutservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("login")
    public CR login(@RequestBody User user) throws Exception {
        String token = userService.login(user);
        if (token == null) {
            return CR.fail("用户名或密码错误");
        }
        return CR.ok(token);
    }

    @PostMapping("register")
    public CR register(@RequestBody User user) throws Exception {
        String username = user.getUsername();
        String password = user.getPassword();
        if (username == null || password == null) {
            return CR.fail("用户名或密码不能为空");
        }
        // 查询是否存在重复的用户名
        User userByUsername = userService.getUserByUsername(username);
        if (userByUsername != null) {
            // 查询到重复的用户记录
            return CR.fail("用户名已存在");
        }
        User add = userService.add(user);
        if (add == null) {
            return CR.fail("注册失败");
        }
        return CR.ok(add);
    }

    @PostMapping("list")
    @Cacheable(value = "list")
    public CR list() {
        return CR.ok(userService.list());
    }

    @PostMapping("getUserByUsername")
    @Cacheable(value = "getUserByUsername", key = "#user.username")
    public CR getUserByUsername(@RequestBody User user) {
        log.info("controller get user by username called");
        return CR.ok(userService.getUserByUsername(user.getUsername()));
    }

    @PostMapping("getUserByUsernameAndEmail")
    @Cacheable(value = "getUserByUsernameAndEmail", key = "#user.username + ':' + #user.email")
    public CR getUserByUsernameAndEmail(@RequestBody User user) {
        log.info("controller get user by username and email called");
        return CR.ok(userService.getUserByUsernameAndEmail(user.getUsername(), user.getEmail()));
    }

    @PostMapping("removeGetUserByUsername")
    @CacheEvict(cacheNames = {"getUserByUsername", "getUserByUsernameAndEmail"}, allEntries = true)
    public CR removeGetUserByUsername() {
        return CR.ok(null);
    }

    @PostMapping("removeUserCache")
    public CR removeUserCache() {
        Boolean b = userService.removeUserCache();
        if (!b) {
            return CR.fail("删除失败");
        }
        return CR.ok(null);
    }


}
